<?php // XenonPHP Startup File
define('HTTP_ROOT', str_replace('//','/',preg_replace('#^(.*)/'.preg_quote(basename(__FILE__),'#').'.*$#i','$1',$_SERVER['PHP_SELF']).'/'));
define('DOCUMENT_ROOT', realpath(dirname(__FILE__))); // Document Root (Example: '/home/USER/public_html') Current file directory by default
define('APPLICATION_ROOT', realpath(dirname(__FILE__).'/application')); // XenonPHP MVC Application directory

// AutoLoad System
spl_autoload_register('X_autoload');
function X_autoload($class){
    $filenames[] = APPLICATION_ROOT."/libs/".$class.".php";
    $filenames[] = APPLICATION_ROOT."/xenonlibs/".$class.".php";
    $filenames[] = APPLICATION_ROOT."/models/".$class.".php";
    foreach ($filenames as $filename) {
        if (is_file($filename)) {
            include $filename;
            break;
        }
    }
}

// Loading Configuration files...
include APPLICATION_ROOT.'/config.php';
include APPLICATION_ROOT.'/mysql_login.php';
include APPLICATION_ROOT.'/database.php';

// ROUTING (Controller, Action, Params and Language)
$PARAMS = explode('/', strstr(substr($_SERVER['REQUEST_URI'], strlen(HTTP_ROOT)).'?','?',true));
define('CONTROLLER', end($PARAMS)? end($PARAMS) : 'index'); array_pop($PARAMS); // By default, Controller is the last item after the last slash in the url. 
define('ACTION', key($_GET)? key($_GET) : 'index'); // By default, Action is the first GET param Key. 
$LANG = (count($PARAMS) && !empty(i18n::$langs_active[reset($PARAMS)]))? array_shift($PARAMS) : null; // Gets the Selected Language from the first PARAM

$modules = array_map('basename', array_filter(glob(APPLICATION_ROOT.'/controllers/*'), 'is_dir'));
define('MODULE', (count($PARAMS) && in_array(reset($PARAMS), $modules))? array_shift($PARAMS) : ''); // Sets the Module (Controller Subdirectory) from the first PARAM
$MODULE = (MODULE? MODULE.'/':'');
if (in_array(CONTROLLER, $modules)) {header('Location: '.CONTROLLER.'/');exit;}

// Main MVC Process Startup
new Xenon();
session_start();
include APPLICATION_ROOT.'/BaseController.php';
if (is_file(APPLICATION_ROOT.'/controllers/'.$MODULE.CONTROLLER.'.php')) {
    include APPLICATION_ROOT.'/controllers/'.$MODULE.CONTROLLER.'.php';
    $controller = new Controller(ACTION, $PARAMS);
    $controller->setLayoutDirectory(APPLICATION_ROOT."/layouts/".$MODULE);
    $controller->setViewDirectory(APPLICATION_ROOT."/views/".$MODULE.CONTROLLER."/");
    $controller->initDatabase();
    $controller->initI18n($LANG); // To use Only hardcoded texts, put Null or False as a second parameter, or put True or nothing to use the current MySQL database
    $controller->init();
    if (method_exists($controller, $controller->action."Action")) {
        call_user_func_array(array($controller, $controller->action."Action"), $_GET);
    }
    $controller->view->renderLayout($controller->layout);
} else {
    header('HTTP/1.1 404 Not Found')&die('<h1>Page Not Found</h1>');
}